package com.bwie.auth.handler;

import com.bwie.common.exceptions.BizException;
import com.bwie.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @ClassName GlobalExceptionHandler
 * @Description 全局异常处理
 * @Author mxy
 * @Date 2025/2/26 10:36
 */
@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    /**
     * 业务异常
     */
    @ExceptionHandler(BizException.class)
    public Result methodBizExceptionHandler(BizException biz){
        log.error("业务异常，异常信息是:{}",biz.getMessage());
        return Result.error(biz.getMessage());
    }

    /**
     * 参数不合法 异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException mane){
        //获取异常信息
        BindingResult bindingResult = mane.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();

        StringBuilder stringBuilder = new StringBuilder();
        allErrors.forEach(allError -> {
            String defaultMessage = allError.getDefaultMessage();
            stringBuilder.append(defaultMessage);
        });

        log.error("参数不合法，异常信息：{}",stringBuilder.toString());

        //验证码不能为空  手机号格式不正确
        return Result.error(stringBuilder.toString());
    }



}
